package com.kj.tms.system.service.user.serviceImpl;


import com.kj.tms.common.bean.dao.BaseMapper;
import com.kj.tms.common.bean.dto.BaseDto;
import com.kj.tms.common.bean.dto.Pager;
import com.kj.tms.common.bean.dto.ReturnData;
import com.kj.tms.common.bean.exception.BusinessException;
import com.kj.tms.common.bean.exception.SessionException;
import com.kj.tms.common.bean.service.BaseService;
import com.kj.tms.common.bean.session.SessionManager;
import com.kj.tms.common.utils.JsonUtils;
import com.kj.tms.common.utils.StringUtil;
import com.kj.tms.common.utils.constant.Consts;
import com.kj.tms.common.utils.encrypt.MD5Util;
import com.kj.tms.common.utils.excel.ExportExcel;
import com.kj.tms.common.utils.uuid.IdGen;
import com.kj.tms.pri.system.menu.dto.ModuleDto;
import com.kj.tms.pri.system.menu.service.ModuleService;
import com.kj.tms.pri.system.org.dto.OrgDto;
import com.kj.tms.pri.system.org.service.OrgService;
import com.kj.tms.pri.system.role.dto.RoleDto;
import com.kj.tms.pri.system.role.service.RoleService;
import com.kj.tms.pri.system.user.dto.QueryUserOrgRoleDto;
import com.kj.tms.pri.system.user.dto.UserDto;
import com.kj.tms.pri.system.user.dto.UserOrgDto;
import com.kj.tms.pri.system.user.dto.UserOrgRoleDto;
import com.kj.tms.pri.system.user.service.UserOrgRoleService;
import com.kj.tms.pri.system.user.service.UserOrgService;
import com.kj.tms.pri.system.user.service.UserService;
import com.kj.tms.system.service.user.dao.UserMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.OutputStream;
import java.sql.Timestamp;
import java.util.*;

/**
 * 类描述： 系统人员Service
 *
 * @author zhangsong
 */
@Service
public class UserServiceImpl extends BaseService<UserDto> implements UserService {
    private static Logger logger = LoggerFactory.getLogger(UserServiceImpl.class);

    @Autowired
    private SessionManager sessionManager;
    @Autowired
    private OrgService orgServiceImpl;
    @Autowired
    private RoleService roleServiceImpl;
    @Autowired
    private UserOrgService userOrgServiceImpl;
    @Autowired
    private UserOrgRoleService userOrgRoleServiceImpl;
    @Autowired
    private ModuleService moduleServiceImpl;
    @Autowired
    private UserMapper userMapper;
    @Override
    public List<UserDto> getAll() {
        return userMapper.listOrgByPage(new UserDto());
    }

    @Override
    public BaseMapper<UserDto> getMapper() {
        return userMapper;
    }

    /**
     * @see UserService#login(String, String, String)
     */
    public List<OrgDto> login(@RequestParam("ip") String ip, @RequestParam("username") String username, @RequestParam("password") String password) {
        UserDto user = userMapper.getByCode(username);
        if (StringUtil.isNotNull(user)) {
            if (!password.equals(user.getPassword())) {
                throw new BusinessException(  Consts.ERROR_PASSWORD_CODE, "密码不正确，请重新录入。");
            }
        } else {
            throw new BusinessException(  Consts.NO_USER, "该用户不存在，请重新录入。");
        }
        if("0".equals(user.getValidMark())){
            throw new BusinessException(  Consts.ERROR, "该用户已被禁用，请咨询管理员！");
        }
        user.setIp(ip);
        List<OrgDto> orgDtos = orgServiceImpl.queryOrgByUser(user.getUserId());
        if (orgDtos.size() == 0) {
            throw new BusinessException(  Consts.NO_ORG_USER, "该用户没有分配机构，请重新录入。");
        } else if (orgDtos.size() == 1) {
            //放入机构信息 到 userDto
            user.setCurUserOrgCode(orgDtos.get(0).getOrgCode());//一个机构直接放入user的当前机构字段 orgCode
            user.setCurUserOrgName(orgDtos.get(0).getOrgName());
            this.changeOrgCode(user);
        }
        user.setOrgDtos(orgDtos);
        //密码不放入session,设置为null
        user.setPassword(null);
        logger.info("#################sessison id :" + sessionManager.getId());
        sessionManager.setAttribute(  Consts.USER, user);
        UserDto users = (UserDto) sessionManager.getAttribute(  Consts.USER);
        return orgDtos;
    }

    /**
     * @see UserService#changeOrgCode(UserDto)
     */
    public UserDto changeOrgCode(@RequestBody(required = false) UserDto user) {
        Map<String, String> map = new HashMap<>();
        map.put("userId", user.getUserId());
        map.put("curUserOrgCode", user.getCurUserOrgCode());
        //放入当前机构编码

        List<RoleDto> roleDtos = roleServiceImpl.listByUserOrg(map);
        if (StringUtil.isNull(roleDtos)) {
            throw new BusinessException(  Consts.NO_ROLE_ORG_USER, "该机构下的用户没有分配角色！");
        }
        user.setRoleDtos(roleDtos);
        //设计二级菜单目录
        getSortUrl(user, map);
        //放入当前机构名称,当前机构code，当前人员信息
        sessionManager.setAttribute(  Consts.USER, user);
        sessionManager.setAttribute(  Consts.CUR_USER_ORG_CODE, user.getCurUserOrgCode());
        sessionManager.setAttribute(  Consts.CUR_USER_ORG_NAME, user.getCurUserOrgName());
        return user;
    }

    //截取二级菜单目录
    public void getSortUrl(UserDto user, Map map) {
        List<ModuleDto> moduleDtos = moduleServiceImpl.queryMenuByUserOrg(map);
        user.setModuleDtos(moduleDtos);
        if (StringUtil.isNotNull(moduleDtos)) {
            Map substrUrlMap = new HashMap();
            String oldUrl;
            for (int i = 0; i < moduleDtos.size(); i++) {
                oldUrl = moduleDtos.get(i).getMenuUrl();
                if (StringUtil.isNotNull(oldUrl)) {
                    String[] strs = oldUrl.split("/");
                    String substrUrl = "";
                    for (int j = 1; j < 3; j++) {
                        substrUrl += "/" + strs[j].trim();
                    }
                    substrUrlMap.put(substrUrl, substrUrl);
                }
            }
            user.setSortUrl(substrUrlMap);
        }
    }

    /**
     * @see UserService#getByCode(Object)
     */
    @Override
    public UserDto getByCode(@RequestBody(required = false)Object code) {
        return userMapper.getByCode(code);
    }

    /**
     * @see UserService#listUserByRole(String)
     */
    @Override
    public List<UserDto> listUserByRole(@RequestParam("Id") String Id) {
        return userMapper.listUserByRole(Id);
    }

    /**
     * @param user
     * @return
     * @throws
     * @method [delete]
     * @description [删除用户]
     * @author 王国庆
     * @version 1.0
     * @date 2017年12月22日 15:16
     */
    @Override
    public void delete(@RequestBody(required = false)UserDto user) {
        //清空与userId关联user表
        userMapper.delete(user);
        //清空与userId关联user_org表
        userOrgServiceImpl.deleteByUser(user.getUserId(), "");
        //清空与userId关联的user_org_role表
        UserOrgRoleDto userOrgRoleDto = new UserOrgRoleDto();
        userOrgRoleDto.setUserId(user.getUserId());
        userOrgRoleServiceImpl.deleteUserOrgRole(userOrgRoleDto);
    }

    /**
     * @see UserService#update(UserDto)
     */
    @Override
    public void update(@RequestBody(required = false)UserDto user) {
        user.setUpdateTime(new Timestamp(System.currentTimeMillis()));
        user.setUpdateUser(((UserDto) sessionManager.getAttribute(  Consts.USER)).getUserId());

        userMapper.update(user);
    }

    @Override
    public void update(@RequestBody Map<String, String> requestParameters,
                       @RequestParam("orgRoleList") String orgRoleList) {
        List<QueryUserOrgRoleDto> queryUserOrgRoleDtosList = JsonUtils.json2List(orgRoleList, QueryUserOrgRoleDto.class);
        //用户信息更改
        UserDto userDto = new UserDto();
        String userId = requestParameters.get("userId");
        userDto.setUserName(requestParameters.get("userName"));
        userDto.setUserCode(requestParameters.get("userCode"));
        userDto.setUserId(userId);
        userDto.setPhoneNo(requestParameters.get("phoneNo"));
        userDto.setEmail(requestParameters.get("email"));
        update(userDto);
        //用户机构角色信息
        //1、添加之前先删除相关中间表信息
        //  1-1）、清空与userId关联user_org表
        userOrgServiceImpl.deleteByUser(userId, "");
        //  1-2）、清空与userId关联的user_org_role表
        UserOrgRoleDto userOrgRoleDto = new UserOrgRoleDto();
        userOrgRoleDto.setUserId(userId);
        userOrgRoleServiceImpl.deleteUserOrgRole(userOrgRoleDto);

        //2、添加关联表信息
        List<UserOrgDto> userOrgDtoList = new ArrayList<>();

        if (queryUserOrgRoleDtosList.size() != 0) {
            for (int i = 0; i < queryUserOrgRoleDtosList.size(); i++) {

                UserOrgDto userOrgDto = new UserOrgDto();
                QueryUserOrgRoleDto queryUserOrgRoleDto = queryUserOrgRoleDtosList.get(i);
                String orgCode = queryUserOrgRoleDto.getOrgCode();
                userOrgDto.setUserId(userId);
                userOrgDto.setOrgCode(orgCode);
                userOrgDtoList.add(userOrgDto);
                List<RoleDto> roleDtoList = queryUserOrgRoleDto.getRoleDtos();
                List<UserOrgRoleDto> userOrgRoleDtoList = new ArrayList<>();
                for (int j = 0; j < roleDtoList.size(); j++) {
                    UserOrgRoleDto userOrgRoleDtos = new UserOrgRoleDto();
                    userOrgRoleDtos.setUserId(userId);
                    userOrgRoleDtos.setOrgCode(orgCode);
                    userOrgRoleDtos.setRoleId(roleDtoList.get(j).getRoleId());
                    userOrgRoleDtoList.add(userOrgRoleDtos);
                }
                //2-2)、添加user_org_role表信息
                userOrgRoleServiceImpl.batchAddUserOrgRole(userOrgRoleDtoList);
            }
            //2-1)、添加user_org表信息
            userOrgServiceImpl.batchAddUserOrg(userOrgDtoList);
        }

    }

    /**
     * @method      [listUser]
     * @description [方法描述]
     * @author      王国庆
     * @version     1.0
     * @param       userDto
     * @return
     * @exception
     * @date        2018年01月02日 15:28
     */
    @Override
    public Pager listUser(@RequestBody(required = false)UserDto userDto) {
        logger.info("用户权限管理主界面，分页查询传入值数据 listUser ---" +
                "userDto：[" + userDto + "]--机构orgCode：[" + userDto.getOrgCode() + "]--角色ID roleId: ["+userDto.getRoleId()+"]");
        if(!StringUtil.isEmptyOrNull(userDto.getOrgCode())){
            userDto.setCurUserOrgCode(userDto.getOrgCode());
        }else {//没有设置机构值默认当前登录机构
            UserDto dto = (UserDto) sessionManager.getAttribute(  Consts.USER);
            String curUserOrgCode = dto.getCurUserOrgCode();
            userDto.setCurUserOrgCode(curUserOrgCode);
        }
        logger.info("查询用户权限管理机构下的人员信息分页数据--listUser--" +
                "传值 userDto[" + userDto + "]---PageNo:" + userDto.getPageNo() + "---PageSize" + userDto.getPageSize());
        Pager pager = userDto.getPager();
        userDto.setEndSize(pager.getPageNo() * pager.getPageSize());
        userDto.setStartSize((pager.getPageNo() - 1) * pager.getPageSize() + 1);
        //访问  查询机构人员列表 方法
        List<UserDto> userDtosList = listOrgByPage(userDto);
        for (UserDto dto : userDtosList) {
            //角色
            Map<String, Object> roleMap = new HashMap<>();
            roleMap.put("userId", dto.getUserId());
            roleMap.put("curUserOrgCode", dto.getOrgCode());
            List<RoleDto> roleDtoList =roleServiceImpl.listByUserOrg(roleMap);
            dto.setRoleDtos(roleDtoList);
        }
        pager.setResults(userDtosList);
        pager.setRowCount(getUserOrgCount(userDto));
        logger.info("查询用户权限管理机构下的人员信息分页数据--listUser--结果集：pager [" + pager.toString() + "]");
        return pager;

    }

    /**
     * @method      [queryOrgByList]
     * @description [模糊匹配查询机构数据到列表]
     * @author      王国庆
     * @version     1.0
     * @param
     * @return
     * @exception
     * @date        2017年12月28日 14:22
     */
    public List<OrgDto>  queryOrgByList(@RequestBody(required = false)OrgDto orgDto){
        return  orgServiceImpl.queryOrgByList(orgDto);
    }
    /**
     * @param requestParameters        用户信息
     * @param orgRoleList 配置的用户机构角色信息
     * @return
     * @throws
     * @method [save]
     * @description [用户信息存储]
     * @author 王国庆
     * @version 1.0
     * @date 2017年12月22日 15:50
     */
    @Override
    public ReturnData save(@RequestBody Map<String, String> requestParameters,
                           @RequestParam("orgRoleList") String orgRoleList) throws Exception {
        Map map = new HashMap<>();
        List<QueryUserOrgRoleDto> queryUserOrgRoleDtosList = JsonUtils.json2List(orgRoleList, QueryUserOrgRoleDto.class);
        map.put("userCode", requestParameters.get("userCode"));
        if (userMapper.getCounts(map) > 0) {
            return new ReturnData(  Consts.ERROR, "用户账号已存在，请重新录入。");
        }
        //1、user表用户信息添加
        UserDto user = new UserDto();
        //新增信息的userId  通过UUID生成
        String userId = IdGen.getId();
        user.setUserId(userId);

        user.setUserCode(requestParameters.get("userCode"));
        user.setUserName(requestParameters.get("userName"));
        user.setPhoneNo(requestParameters.get("phoneNo"));
        user.setEmail(requestParameters.get("email"));

        user.setCreateUser(((UserDto) sessionManager.getAttribute(  Consts.USER)).getUserId());
        user.setCreateTime(new Timestamp(System.currentTimeMillis()));
        user.setValidMark(  Consts.VALID_MARK_1);
        user.setDelMark(  Consts.DEL_MARK_0);
        user.setPassword(MD5Util.getMD5Code(  Consts.PASSWORD_INITIAL));
        userMapper.save(user);

        //2、添加关联表信息
        List<UserOrgDto> userOrgDtoList = new ArrayList<>();
        if (queryUserOrgRoleDtosList.size() != 0) {
            for (int i = 0; i < queryUserOrgRoleDtosList.size(); i++) {

                UserOrgDto userOrgDto = new UserOrgDto();
                QueryUserOrgRoleDto queryUserOrgRoleDto = queryUserOrgRoleDtosList.get(i);
                String orgCode = queryUserOrgRoleDto.getOrgCode();
                userOrgDto.setUserId(userId);
                userOrgDto.setOrgCode(orgCode);
                userOrgDtoList.add(userOrgDto);
                List<RoleDto> roleDtoList = queryUserOrgRoleDto.getRoleDtos();
                List<UserOrgRoleDto> userOrgRoleDtoList = new ArrayList<>();
                for (int j = 0; j < roleDtoList.size(); j++) {
                    UserOrgRoleDto userOrgRoleDtos = new UserOrgRoleDto();
                    userOrgRoleDtos.setUserId(userId);
                    userOrgRoleDtos.setOrgCode(orgCode);
                    userOrgRoleDtos.setRoleId(roleDtoList.get(j).getRoleId());
                    userOrgRoleDtoList.add(userOrgRoleDtos);
                }
                //2-2)、添加user_org_role表信息
                userOrgRoleServiceImpl.batchAddUserOrgRole(userOrgRoleDtoList);
            }
            //2-1)、添加user_org表信息
            userOrgServiceImpl.batchAddUserOrg(userOrgDtoList);
        }
        return new ReturnData(  Consts.SUCCESS, "添加用户成功。");
    }

    /**
     * @param dto
     * @param oldPwd
     * @Title: modifyPassword
     * @Description 用户密码修改
     * @Method modifyPassword
     * @Return boolean
     * @Date: 2017年11月02日 9:48
     * @Author:wangguoqing
     * @version: 2017年11月02日
     */
    public boolean updatePassword(@RequestBody(required = false)UserDto dto, @RequestParam("oldPwd") String oldPwd) throws Exception {
        if (oldPwd != null) {
            UserDto dto1 = getMapper().getById(dto);
            if (!dto1.getPassword().equals(MD5Util.getMD5Code(oldPwd))) {
                return false;             //"旧密码输入不正确！"
            }
        }
        if (dto.getPassword() != null) {
            String pass = MD5Util.getMD5Code(dto.getPassword());
            dto.setPassword(pass);
            //获取修改人员（即当前登录人员）
            dto.setUpdateUser(dto.getUserId());

            //获取当前登陆时间
            //String curDate= DateUtil.sdfLongTimePlus.format(new Date());
            Timestamp curDate = new Timestamp(System.currentTimeMillis());
            dto.setUpdateTime(curDate);
        }

        userMapper.update(dto);
        return true;
    }

    /**
     * @see UserService#listByConditionNoPage(UserDto)
     */
    @Override
    public List<UserDto> listByConditionNoPage(@RequestBody(required = false)UserDto userDto) {
        if(!StringUtil.isEmptyOrNull(userDto.getOrgCode())){
            userDto.setCurUserOrgCode(userDto.getOrgCode());
        }else {//没有设置机构值默认当前登录机构
            UserDto dto = (UserDto) sessionManager.getAttribute(  Consts.USER);
            String curUserOrgCode = dto.getCurUserOrgCode();
            userDto.setCurUserOrgCode(curUserOrgCode);
        }
        List<UserDto> userDtoList = userMapper.listByConditionNoPage(userDto);
        for (UserDto dto : userDtoList) {
            //角色
            Map<String, Object> roleMap = new HashMap<>();
            roleMap.put("userId", dto.getUserId());
            roleMap.put("curUserOrgCode", dto.getOrgCode());
            List<RoleDto> roleDtoList = roleServiceImpl.listByUserOrg(roleMap);
            StringBuffer roleStr = new StringBuffer();
            for(int i = 0 ; i< roleDtoList.size() ;i++){
                String roleName = roleDtoList.get(i).getRoleName();
                if(i==0) {
                    roleStr.append(roleName);
                }else {
                    roleStr.append(","+roleName);
                }
            }
            dto.setRoleNameList(roleStr.toString());
        }
        return userDtoList;
    }

    /**
     * 用户选择机构进行登录
     *
     * @see UserService#loginIndex(String, String)
     */
    @Override
    public UserDto loginIndex(@RequestParam("orgCode") String orgCode, @RequestParam("orgName") String orgName) {
        logger.info("#################sessison id :" + sessionManager.getId());
        UserDto user = (UserDto) sessionManager.getAttribute(  Consts.USER);
        if (StringUtil.isNull(user)) {
            throw new SessionException("登录超时！");
        }

        logger.info("sessison id :" + sessionManager.getId());
        if (orgCode != null) {
            user.setCurUserOrgCode(orgCode);
            user.setCurUserOrgName(orgName);
            try {
                //根据机构ID 人员ID 查询 角色信息等
                changeOrgCode(user);
                //通过当前机构查询当前纳税主体信息
            } catch (Exception e) {
                logger.error(e.toString());
            }
        }
        return user;
    }

    /**
     * @param userDto 用户信息Id
     * @return Pager
     * @throws
     * @method [listOrgRoleByPage]
     * @description [加载配置机构权限信息]
     * @author 王国庆
     * @version 1.0
     * @date 2017年12月11日 17:35
     */
    @Override
    public List<UserOrgDto> listOrgRoleByPage(@RequestBody(required = false)UserDto userDto) {
        logger.info("用户权限管理主界面，分页查询传入值数据 listOrgRoleByPage ---" +
                "userDto：[" + userDto + "]");
        Map<String, Object> map = new HashMap<String, Object>();
        if (!StringUtil.isBlank(userDto.getUserId())) {
            map.put("userId", userDto.getUserId());
        }
        map.put("validMark",   Consts.VALID_MARK_1);
        logger.info("查询用户权限管理机构下的人员信息分页数据--listOrgRoleByPage--" +
                "传值 map[" + map + "]---PageNo:" + userDto.getPageNo() + "---PageSize" + userDto.getPageSize());
        //访问  查询机构人员列表 方法
        List<UserOrgDto> userOrgRoleDtoList = userOrgServiceImpl.listOrgRoleByPage(map);
        //角色
        for (UserOrgDto dto : userOrgRoleDtoList) {
            Map<String, Object> roleMap = new HashMap<>();
            roleMap.put("userId", userDto.getUserId());
            roleMap.put("curUserOrgCode", dto.getOrgCode());
            dto.setRoleDtos(roleServiceImpl.listByUserOrg(roleMap));
        }
        //logger.info("查询用户权限管理机构下的人员信息分页数据--listOrgRoleByPage--结果集：pager [" + pager.toString() + "]");
        return userOrgRoleDtoList;
    }

    /**
     * @param userDto 用户信息Id
     * @param orgCode 当前登录机构编码
     * @param orgName 机构名称
     * @return Pager
     * @throws
     * @method [listOrgByUserOrgPage]
     * @description [根据当前机构加载配置机构权限分页信息]
     * @author 王国庆
     * @version 1.0
     * @date 2017年12月14日 16:12
     */
    @Override
    public List<UserOrgDto> listOrgByUserOrgPage( @RequestBody(required = false)UserDto userDto ,
                                                             @RequestParam("orgCode") String orgCode,
                                                             @RequestParam("orgName") String orgName) {
        //获取session值
        UserDto user = (UserDto) sessionManager.getAttribute(  Consts.USER);
        String curUserOrgCode = user.getCurUserOrgCode();
        logger.info("用户权限管理主界面，分页查询传入值数据 listOrgByUserOrgPage ---" +
                "userDto：[" + userDto + "]");
        Map<String, Object> map = new HashMap<String, Object>();
        if (!StringUtil.isBlank(userDto.getUserId())) {
            map.put("userId", userDto.getUserId());
        }
        if (!StringUtil.isBlank(orgName)) {
            map.put("orgName", orgName);
        }
        if (!StringUtil.isBlank(orgCode)) {
            map.put("orgCode", orgCode);
        }
        map.put("curUserOrgCode", curUserOrgCode);
        map.put("validMark",   Consts.VALID_MARK_1);
        logger.info("根据当前机构加载配置机构权限分页信息--listOrgByUserOrgPage--" +
                "传值 map[" + map + "]---PageNo:" + userDto.getPageNo() + "---PageSize" + userDto.getPageSize());
        List<UserOrgDto> userOrgRoleDtoList = userOrgServiceImpl.listOrgByUserOrgPage(map);
        //角色
        for (UserOrgDto dto : userOrgRoleDtoList) {
            Map<String, Object> roleMap = new HashMap<>();
            roleMap.put("userId", userDto.getUserId());
            roleMap.put("curUserOrgCode", dto.getOrgCode());
            dto.setRoleDtos(roleServiceImpl.listByUserOrg(roleMap));
        }
        return userOrgRoleDtoList;
    }

    /**
     * @param dto 角色信息
     * @return Pager
     * @throws
     * @method [listOrg]
     * @description [加载配置机构权限信息]
     * @author 王国庆
     * @version 1.0
     * @date 2017年12月11日 17:35
     */
    @Override
    public Pager listOrg(@RequestBody(required = false) OrgDto dto) {

        return null;
    }

    /**
     * @param
     * @return
     * @throws
     * @method [exportData]
     * @description [用户信息导出]
     * @author 王国庆
     * @version 1.0
     * @date 2017年12月14日 16:29
     */
    @Override
    public ResponseEntity<byte[]> exportData(@RequestBody UserDto userDto) {

        List<UserDto> dtos = listByConditionNoPage(userDto);
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        OutputStream out = null;
        ByteArrayInputStream inputStream = null;
//        response.setContentType("octets/stream");
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("title", "用户管理信息");
        String[] headers = {"登录账号", "姓名", "手机号码", "邮箱", "状态","机构编码","机构名称","角色"};
        String[] cols = {"userCode", "userName", "phoneNo", "email", "validMarkName","orgCode","orgName","roleNameList"};
        paramMap.put("listData", dtos);
        paramMap.put("headers", headers);
        paramMap.put("cols", cols);

        try {
            String fileName = new String("用户管理信息.xls".getBytes("gbk"), "iso-8859-1");
//            response.addHeader("Content-Disposition",
//                    "attachment;filename=" + filename + ".xls");
            exportExcel(outputStream, paramMap);
            inputStream = new ByteArrayInputStream(outputStream.toByteArray());
//            out = response.getOutputStream();
//            int i;
//            while ((i = inputStream.read()) != -1) {
//                out.write(i);
//            }
            HttpHeaders httpHeaders = new HttpHeaders();
            httpHeaders.setContentType(MediaType.APPLICATION_OCTET_STREAM);//APPLICATION_OCTET_STREAM是以流的形式下载文件，这样可以实现任意格式的文件下载。
            httpHeaders.setContentDispositionFormData("attachment", fileName);
            return new ResponseEntity<byte[]>(outputStream.toByteArray(),httpHeaders, HttpStatus.CREATED);
        } catch (Exception e) {
//            response.setContentType("text/plain");
//            response.reset();
            throw new BusinessException("导出excel出错！", e);
        } finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (inputStream != null) {
                    inputStream.close();
                }
                outputStream.close();
            } catch (Exception e) {
                throw new BusinessException("导出excel出错！", e);
            }

        }
    }

    /**
     * @param userDto
     * @return List<UserDto> 返回类型
     * @throws Exception
     * @Title: listOrgByPage
     * @Author:wangguoqing
     * @Description: 查询机构人员列表分页
     */
    private List<UserDto> listOrgByPage(UserDto userDto) {
        return userMapper.listOrgByPage(userDto);
    }


    /**
     * @param userDto
     * @Title: getUserOrgCount
     * @Description 查询机构人员列表数量
     * @Method
     * @Return
     * @Date: 2017年10月25日 10:28
     * @Author:wangguoqing
     * @version: 2017年10月25日
     */
    private int getUserOrgCount(UserDto userDto) {
        return userMapper.getUserOrgCount(userDto);
    }

    /**
     * @param map
     * @return List<UserDto> 返回类型
     * @throws Exception
     * @Title: listWaitUser
     * @Description: 查询等待分配的机构人员分页数据
     */
    public List<UserDto> listWaitUser(@RequestBody(required = false)Map map) {
        return userMapper.listWaitUser(map);
    }

    /**
     * @param map
     * @Title: getWaitUserCount
     * @Description 查询等待分配的机构人员分页数据数量
     * @Method
     * @Return
     * @Date: 2017年10月25日 10:28
     * @Author:wangguoqing
     * @version: 2017年10月25日
     */
    public int getWaitUserCount(@RequestBody(required = false)Map map) {
        return userMapper.getWaitUserCount(map);
    }

    @Override
    public ReturnData saveListUserDtoByExcel(@RequestBody(required = false)List<UserDto> list) {
        //批量导入调用触发器
        userMapper.batchAddUserOrgRole(list);
        return new ReturnData(  Consts.SUCCESS, "导入共获取"+list.size()+"条数据！");
    }

    /**
     * @method      [initRole]
     * @description [初始化角色数据]
     * @author      王国庆
     * @version     1.0
     * @param       roleId 角色ID
     * @return
     * @exception
     * @date        2018年01月02日 17:56
     */
    @Override
    public List<RoleDto> initRole(@RequestParam(value = "roleId", required = false)  String roleId){
        return  roleServiceImpl.list( roleId);
    }


    /**
     * @method      [queryMutexByRoleNames]
     * @description [根据角色名称查询互斥角色]
     * @author      王国庆
     * @version     1.0
     * @param       roleNames 角色名称数组 以,分开
     * @return      String
     * @exception
     * @date        2018年01月23日 16:56
     */
    @Override
    public ReturnData queryMutexByRoleNames(@RequestParam("roleNames")String roleNames) {
        String[] roleNameList = roleNames.split(",");
        for (int i = 0; i < roleNameList.length; i++) {
            String roleName =roleNameList[i];
            List<RoleDto> roleDtoList = roleServiceImpl.queryMutexByList(roleName);
            String mutex = roleDtoList.get(0).getMutex();
            if (!StringUtil.isEmptyOrNull(mutex)) {
                String[] mutexList = mutex.split("，");
                StringBuffer mutexNameList = new StringBuffer();
                for (int j = 0; j < mutexList.length; j++) {
                    String roleId = mutexList[j];
                    RoleDto roleDto = roleServiceImpl.queryMutexNameByList(roleId);
                    String roleDtoName = roleDto.getRoleName();
                    if (j == 0) {
                        mutexNameList.append(roleDtoName);
                    } else {
                        mutexNameList.append("," + roleDtoName);
                    }
                }
                //比较 roleNameList ，mutexNameList含有的相同角色名称
                List<String> str = getAllSameElement(roleNameList,mutexNameList.toString().split(","));
                if(!StringUtil.isEmptyOrNull(str) && str.size() > 0){
                    return new ReturnData(  Consts.ERROR, roleName + "与(" + str + ")角色互斥，不能同时设置！");

                }
            }
        }
        return new ReturnData(  Consts.SUCCESS, "角色配置成功！");
    }

    /**
     * @method      [getAllSameElement]
     * @description [两个字符串数组中的相同元素]
     * @author      王国庆
     * @version     1.0
     * @param       strArr1
     * @param       strArr2
     * @return      List<String>
     * @exception
     * @date        2018年01月24日 9:51
     */
    private List<String> getAllSameElement(String[] strArr1,String[] strArr2) {

        if(strArr1 == null || strArr2 == null) {
            return null;
        }
        List<String> strList1 = new ArrayList<String>(Arrays.asList(strArr1)); //----------代码段1
        List<String>  strList2 = new ArrayList<String>(Arrays.asList(strArr2));  //--------------代码段2
        strList1.retainAll(strList2);
        return strList1;
    }
    /**
     * 导出
     *
     * @param outputStream
     * @param parameterMap
     */
    private void exportExcel(OutputStream outputStream, Map parameterMap) {
        List<Map> mapData = null;
        List list = (List) parameterMap.get("listData");
        if (list != null && list.size() > 0) {
            Object object = list.get(0);
            if (object instanceof BaseDto) {
                try {
                    mapData = ExportExcel.Object2Map(list, "");
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else {
                mapData = list;
            }
        }
        String title = (String) parameterMap.get("title");
        String describe = (String) parameterMap.get("describe");
        String[] headers = (String[]) parameterMap.get("headers");
        String[] cols = (String[]) parameterMap.get("cols");
        ExportExcel.exportExcel(outputStream, title, describe, headers, cols, mapData);
    }
}
